import { Controller } from 'egg';
import * as path from 'path';
import sendToWormhole from 'stream-wormhole';
import { createWriteStream } from 'fs';

class UploadController extends Controller {
  /**
   * 上传图片
   */
  public async upload() {
    const { ctx } = this;
    const stream = await this.ctx.getFileStream();
    if (stream.filename) {
      const basename = path.basename(stream.filename).split('.');
      const len = basename.length - 1;
      const imgUrl = basename[len]; // 文件后缀
      const newName = this.ctx.helper.genImgName() + '.';
      const newUrl = newName + imgUrl;
      const localFilePath = path.join(__dirname, "../public/img", newUrl); //本地文件相对位置
      try {
        stream.pipe(createWriteStream(localFilePath));
        const result2: any = await new Promise((resolve) => {
          stream.on("end", function () {
              resolve({ code: 1, msg: '上传图片成功' });
          });
        });
        if (result2.code === 1) {
          const returnData = { imgName: newUrl };
          ctx.body = ctx.helper.responseSuccess('上传成功', returnData);
        } else {
          ctx.body = ctx.helper.responseErrorMsg(result2.msg);
        }
      } catch (e) {
        ctx.body = ctx.helper.responseErrorMsg('上传失败');
      }
    } else {
      await sendToWormhole(stream);
      ctx.body = ctx.helper.responseErrorParam('请上传文件');
    }
  }

  /**
   * 从微信服务器下载图片
   */
  public async uploadImage() {
    const { ctx, ctx: { request } } = this;
    try {
      ctx.validate({
        serverId: 'string'
      }, request.body)
    } catch (e) {
      ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
      return;
    }
    const result = await ctx.service.uploadService.uploadImage(request.body);
    ctx.body = ctx.helper.responseSuccess('上传成功', result);
  }

  /**
   * 导出excel报名表
   */
  public async exportExcel() {
    const { ctx, ctx: { query } } = this;
    try {
      ctx.validate({
        activity_id: 'string'
      }, query)
    } catch (e) {
      ctx.body = ctx.helper.responseErrorParam(e.errors[0].message);
      return;
    }
    const result: any = await ctx.service.uploadService.exportExcel(query);
    ctx.attachment(result.name);
    ctx.body = result.data;
  }
}
export default UploadController;